# Request对象示例
from flask import request, jsonify
from app.api import api_bp
from app.utils.response import response_success

@api_bp.route('/request-demo', methods=['GET', 'POST', 'PUT', 'DELETE'])
def request_demo():
    """演示request对象的各种用法"""
    
    # 1. 获取请求方法
    method = request.method
    
    # 2. 获取URL信息
    url = request.url
    base_url = request.base_url
    path = request.path
    
    # 3. 获取查询参数 (GET请求的参数)
    # 例如: /request-demo?name=John&age=25
    query_params = {
        'name': request.args.get('name', default='Guest'),
        'age': request.args.get('age', type=int, default=0)
    }
    
    # 4. 获取请求头信息
    user_agent = request.headers.get('User-Agent')
    content_type = request.headers.get('Content-Type')
    
    # 5. 获取表单数据 (表单提交)
    form_data = {}
    if request.form:
        form_data = dict(request.form)
    
    # 6. 获取JSON数据 (POST/PUT请求的JSON体)
    json_data = {}
    if request.is_json:
        json_data = request.get_json() or {}
    
    # 7. 获取原始请求体
    raw_data = request.get_data(as_text=True) if request.data else ""
    
    # 8. 获取文件上传
    files_info = {}
    if request.files:
        for key, file in request.files.items():
            files_info[key] = {
                'filename': file.filename,
                'content_type': file.content_type,
                'size': len(file.read())
            }
            file.seek(0)  # 重置文件指针
    
    # 9. 获取客户端信息
    client_info = {
        'ip_address': request.remote_addr,
        'host': request.host,
        'scheme': request.scheme  # http或https
    }
    
    # 10. 获取Cookie
    cookies = dict(request.cookies)
    
    # 返回所有收集到的信息
    result = {
        'method': method,
        'url_info': {
            'url': url,
            'base_url': base_url,
            'path': path
        },
        'query_params': query_params,
        'headers': {
            'user_agent': user_agent,
            'content_type': content_type
        },
        'form_data': form_data,
        'json_data': json_data,
        'raw_data': raw_data[:100] + '...' if len(raw_data) > 100 else raw_data,
        'files': files_info,
        'client_info': client_info,
        'cookies': cookies
    }
    
    return response_success(data=result)